package com.yu.springboot_project_yu.controller;

import com.yu.springboot_project_yu.common.Result;
import com.yu.springboot_project_yu.entity.User;
import com.yu.springboot_project_yu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result<User> register(@RequestBody User user) {
        // 检查用户名是否已存在
        if (userService.findByUsername(user.getUsername()) != null) {
            return Result.error("用户名已存在");
        }
        
        // 设置默认值
        user.setCreateTime(new Date());
        user.setStatus(1);
        
        return Result.success(userService.save(user));
    }

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody User user) {
        User existUser = userService.findByUsername(user.getUsername());
        if (existUser != null && existUser.getPassword().equals(user.getPassword())) {
            Map<String, Object> data = new HashMap<>();
            data.put("token", "mock-token-" + System.currentTimeMillis());
            data.put("user", existUser);
            return Result.success(data);
        }
        return Result.error("用户名或密码错误");
    }
}